package dk.zpon.andnoise;

import java.util.Stack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import dk.zpon.andnoise.BrowserAdapter.FilefolderHolder;
import dk.zpon.andnoise.R;

public class Browser extends ListActivity{

	private Connection mCon;
	private TextView mPath;
	private String mCurrentDir;
	private Stack<BrowserAdapter> mAdapterStack;
	final private int MENU_ADD_ALL = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browser);

		mAdapterStack = new Stack<BrowserAdapter>();

		setListAdapter(new BrowserAdapter(this));

		mCon = Connection.getInstance();

		this.mPath = (TextView)this.findViewById(R.id.browser_path);
		this.mCurrentDir = mCon.browserGetCurrentPath();
		mPath.setText("Current path: "+mCurrentDir);
	}

	protected Dialog onCreateDialog(final int position)
	{
		CharSequence[] userItems = {"Information", "Add to playlist"};
		CharSequence[] adminItems = {"Information", "Add to playlist", "Play now"};

		final Context context = this;
		final CharSequence[] items = (mCon.getUsertype() == Usertype.user ? userItems : adminItems);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose an action");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if(item == 0)
				{
					dialog.cancel();
					showInfo(position);
				}
				// Add to playlist
				else if(item == 1)
				{
					mCon.playlistAddTrack((mCurrentDir.charAt(mCurrentDir.length()-1) == '/' ? mCurrentDir : mCurrentDir+"/")+((BrowserAdapter)getListAdapter()).getHolder(position).getName());
				}
				// Play now
				else
				{
					mCon.playbackOpen((mCurrentDir.charAt(mCurrentDir.length()-1) == '/' ? mCurrentDir : mCurrentDir+"/")+((BrowserAdapter)getListAdapter()).getHolder(position).getName());
				}
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	public boolean onCreateOptionsMenu(Menu menu)
	{
		if(mCon.getUsertype() == Usertype.admin)
			menu.add(0, MENU_ADD_ALL, 0, "Add all files to playlist");
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ADD_ALL:
			try {
				JSONArray files = this.mCon.browserGetCurrentFilesAndFolders().getJSONArray("FILES");

				for(int i = 0; i < files.length(); i++)
					mCon.playlistAddTrack(mCon.browserGetCurrentPathAppendedWithSlash()+files.get(i));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return true;
		}
		return false;
	}

	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		FilefolderHolder holder = (FilefolderHolder)v.getTag();
		if(holder.isFolder())
		{
			if(holder.getIsUpOneLevel())
			{
				String[] split;

				if(mCurrentDir.startsWith("/"))
					split = mCurrentDir.substring(1).split("/");
				else
					split = mCurrentDir.split("/");

				String name = "/";

				int removeLast = 0;
				if(split[split.length-1].equals(null))
					removeLast = 2;
				else
					removeLast = 1;

				for(int i = 0; i < split.length-removeLast; i++)
					name += split[i] + "/";

				mCon.browserGoto(name);

				if(mAdapterStack.size() > 0)
				{
					BrowserAdapter adapter = this.mAdapterStack.pop();
					setListAdapter(adapter);
					// Restore approximate scroll position
					getListView().setSelectionFromTop(adapter.getFirstVisible(), 0);
				}
				else
					setListAdapter(new BrowserAdapter(this));
			}
			else
			{
				BrowserAdapter adapter = (BrowserAdapter)getListAdapter();
				// Save scroll position
				adapter.setFirstVisible(this.getListView().getFirstVisiblePosition());
				mCon.browserGoto(holder.getName());

				this.mAdapterStack.push(adapter);
				setListAdapter(new BrowserAdapter(this));
			}

			this.mCurrentDir = mCon.browserGetCurrentPath();
			mPath.setText("Current path: "+mCurrentDir);

		}
		else
		{
			showDialog(((FilefolderHolder)v.getTag()).getPosition());
		}
	}
	
	private void showInfo(int position)
	{
		JSONObject obj = mCon.browserGetInfo(mCon.browserGetCurrentPathAppendedWithSlash()+((BrowserAdapter)getListAdapter()).getHolder(position).getName());
		if(obj != null)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			String text;
			try {
				text = "<b>Title:</b> " + obj.getString("TITLE")+"<br/>"+
						"<b>Artist:</b> "+obj.getString("ARTIST")+"<br/>"+
						"<b>Album:</b> "+obj.getString("ALBUM")+"<br/>"+
						"<b>Track number:</b> "+Integer.toString(obj.getInt("TRACKNUM"))+"<br/>"+
						"<b>Genre:</b> "+obj.getString("GENRE");
			} catch (JSONException e) {
				text = "<b>Title:</b><br/>"+
				"<b>Artist:</b><br/>"+
				"<b>Album:</b><br/>"+
				"<b>Track number:</b><br/>"+
				"<b>Genre:</b>";
			}
				builder.setMessage(Html.fromHtml(text))
					   .setTitle(((BrowserAdapter)getListAdapter()).getHolder(position).getName())
				       .setCancelable(true)
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
}
